<?php

/**
 * 外部接口
 * @author chenchao
 * @version 1.0
 */

//include ROOT_PATH . '/appService/app.config.php';
include ROOT_PATH . '/includes/lib.rayhttp.php';
include_once ROOT_PATH . '/UE/libs/Cache.php';
include_once ROOT_PATH . '/includes/lib.logs.php';

class Transport_http_call extends RayHttp {
    private $_baseUrl;

    private $_appkey;
    private $_version;
    private $_format;
    private $_sig;

    private $_cache;
    private $_useCache;
    
    private $_log;

    public function __construct($ocnfigs = array()) {
        $this->Transport_http_call ( $ocnfigs );
    }

    public function Transport_http_call($configs = array()) {
        $this->setParams ();
        parent::__construct ( $configs );
    }

    /**
     * 设置相关参数
     */
    public function setParams() {
        $this->setBaseUrl ();

        $this->setAppKey ();
        $this->setVersion ();
        $this->setFormat ();
        $this->setSig ();

        $this->getCache ();
    }

    /**
     * 设置外部接口基地址
     * @param Boolean $random
     */
    public function setBaseUrl($random = true) {
        $app_server = unserialize(APP_BASE_URL);
        if ($random && count ( $app_server ) > 1) {
            $randomid = array_rand ( $app_server );
            if ($app_server[$randomid])
                $url = $app_server[$randomid]['protocol'] . '://' . $app_server[$randomid] ['url'];
            else
                $url = '';
        } else {
            $url = $app_server [0] ['protocol'] . '://' . $app_server [0] ['url'];
        }

        $this->_baseUrl = $url;
    }
    public function setAppKey($appkey = APP_TRANPORT_APPKEY) {
        $this->_appkey = $appkey;
    }
    public function setVersion($version = APP_TRANPORT_VERSION) {
        $this->_version = $version;
    }
    public function setFormat($format = APP_TRANPORT_FORMAT) {
        $this->_format = $format;
    }
    public function setSig($sig = APP_TRANPORT_SIG) {
        $this->_sig = $sig;
    }
    /**
     * 是否使用缓存
     * @param Boolean $useCache
     */
    public function useCache($useCache = true) {
        $this->_useCache = $useCache;
    }

    /**
     * 取缓存
     */
    public function getCache() {
        if (! $this->_cache) {
            $this->_cache = UE_Cache::getInstance ( APP_CACHE_TYPE );
        }
        return $this->_cache;
    }

    /**
     * 判断是否缓存
     * @param Mixed $cachedId
     * @return Boolean
     */
    public function isCached($cachedId) {
        $rs = $this->_cache->get ( $cachedId );
        if (!empty($rs) && $rs!==false)
            return true;
        else
            return false;
    }

    /**
     * 取CACHE KEY
     * @param Mixed $cachedId
     * @return String cacheKey
     */
    public function getCacheKey($cachedId) {
        return md5 ( serialize ( $cachedId ) );
    }

    private function _do_urlencode_args($args) {
        if (is_array ( $args )) {
            foreach ( $args as $key => $val ) {
                $args [$key] = $this->_do_urlencode_args ( $val );
            }
            return $args;
        } elseif (is_string ( $args )) {
            return trim ( $args );
        } else {
            return $args;
        }
    }

    /**
     * 记录日志
     * @param $arr       日志内容	
     * @param $filename  日志名称
     * @param $dir       日志目录
     * @return String cacheKey
     */
    function set_logs($arr,$filename='',$dir='')
    {
         if(defined ( 'LOGS_IS_ON' ) && LOGS_IS_ON)
         {
            if(!is_object($this->_log))
            {
            	$this->_log = new Logs();	
            }
            $dir = $dir? $dir : LOGS_PATH;
            $filename = $filename? $filename : date('Y-m-d',time()).'.log';
            $logs=new Logs($dir,$filename);
            $logs->setLog($arr);
         }
    }
    
    
    function microtimeFloat()
	{
		list($usec, $sec) = explode(" ", microtime());
		return ((float)$usec + (float)$sec);
	}
    /**
     * 请求服务所提供的接口方法
     * @param String $reqMethod 接口方法
     * @param Mixed $postData 请求数据
     * @param Int $timeout 超时时间
     * @param Boolean $useCache 是否使用缓存
     * @return JSON_OBJECT
     */
    public function request($reqMethod, $args = array(), $timeout = APP_TRANPORT_TIMEOUT, $useCache = true,$httpdebug=0) {

        //判定缓存、随机请求服务器
        $cacheId = $this->getCacheKey ( $reqMethod . implode ( '', $args ) );
        if (defined ( 'USE_APP_CACHE' ) && USE_APP_CACHE == 1 && $useCache && $this->isCached ( $cacheId )) {
            $res = $this->_cache->get ( $cacheId );
            return unserialize ( $res );
        }else{
            $params = array ();
            if (count ( $args ) > 0) {
                if (! is_array ( $args )) {
                    $args = array ($args );
                }
                foreach ( $args as $k => $v ) {
                    $params [$k] =  ( $this->_do_urlencode_args ( $v ) );
                }
            }

            $params ['method'] = $reqMethod;

            $params ['appkey'] = $this->_appkey;
            $params ['v'] = $this->_version;
            $params ['format'] = $this->_format;
            $params ['sig'] = $this->_sig;

            $method = APP_TRANPORT_METHOD;
            //记录日志  请求
            $startdate = $this->microtimeFloat();
         
if($httpdebug)
{
    echo '请求参数：'."<br>";
    pr($params);
}
	       /* try{
	            $res = parent::$method ( $this->_baseUrl, $params, $timeout);
	        }
	        catch(Exception $e)
	        {
	             $this->setBaseUrl();
	             $res = parent::$method ( $this->_baseUrl, $params, $timeout);
	        }*/

			if($timeout==1)
			{
			    $timeout==APP_TRANPORT_TIMEOUT;
			}
            $res = parent::$method ( $this->_baseUrl, $params, $timeout);
if($httpdebug)
{
    echo '返回json格式：'."<br>";
    echo $res;
}
            //记录日志
            $enddate = $this->microtimeFloat();

            $createdate = date("Y-m-d H:i:s");     
            $logsArr = array(
			    'method'=>$reqMethod,
			    'reqdata'=>json_encode($params),  
			    'reqtime'=>$startdate,  
			    'rettime'=>$enddate,  
			    'retdata'=>addslashes($res),  
			    'requrl'=>$this->_baseUrl,  
			    'runtime'=>$enddate-$startdate,  
			    'timeout'=>$timeout,
			    'createdate'=>$createdate ,
                'appact'=> $_SERVER['REQUEST_URI'], 
			);
            
            
           // $this->set_logs(str_pad('', 150, "--*--") );
//            $this->set_logs(serialize($logsArr));
           // $this->set_logs($logsArr);
            $this->set_logs("--*--");
            $this->set_logs(serialize($logsArr));
            if (defined ( 'USE_APP_CACHE' ) && USE_APP_CACHE == 1 && $useCache && $this->isCached ( $cacheId )) {
                $this->_cache->set ( $cacheId, serialize ( $res ) );
            }
        }

        if (!empty($res) && strlen ( $res ) > 0) {
            if (defined('APP_TRANPORT_RETURN_ARRAY') && APP_TRANPORT_RETURN_ARRAY==1) {//返回为数组
            	$re_arr = json_decode($res, true);
                $re_arr = empty($re_arr) ? array() : $re_arr;
            	//判断是否返回错误，或者列表是空的情况，则直接返回缓存
            	if(isset($re_arr['code']) || (array_key_exists('item',$re_arr) && empty($re_arr['results']['item'])))
            	{
            		if (defined ( 'USE_APP_CACHE' ) && USE_APP_CACHE == 1 && $useCache && $this->isCached ( $cacheId )) {
			            $res = $this->_cache->get ( $cacheId );
			            return unserialize ( $res );
            		}
            	}
            	//判断是否返回错误，或者列表是空的情况，则直接返回缓存%**** 结束
                return $re_arr;
            }else
                return ecm_json_decode ( $res );
        } else {
            return null;
        }
    }

}

